const db = uniCloud.database()
const dbCmd = db.command

exports.main = async (event, context) => {
	const {
		user_id,
		target_grade
	} = event
	let transaction = null

	// 参数校验
	if (!user_id || !target_grade) {
		return {
			code: 400,
			msg: '参数错误'
		}
	}

	try {
		// 1. 获取会员等级文档
		const gradeRes = await db.collection('jlg-parameter').doc(target_grade).get()
		console.log(gradeRes, 'gradeRes_________')
		if (!gradeRes) {
			return {
				code: 404,
				msg: '该会员等级不存在'
			}
		}
		const gradeDoc = gradeRes.data[0]
		const requiredScore = gradeDoc.price

		// 2. 获取用户当前信息
		const userRes = await db.collection('uni-id-users').doc(user_id).get()
		const userData = userRes.data[0]
		console.log(userData, 'userData______')
		if (!userData) {
			return {
				code: 404,
				msg: '用户不存在'
			}
		}

		// 校验积分是否足够
		console.log(userData.score, requiredScore)
		if (userData.score < requiredScore) {
			return {
				code: 403,
				msg: '积分不足'
			}
		}

		// 3. 计算有效期
		const openingTime = Date.now()
		const failureTime = openingTime + 365 * 24 * 60 * 60 * 1000 // 1年有效期

		// // 4. 开启事务
		transaction = await db.startTransaction()

		// 5. 更新用户信息
		const newScore = userData.score - requiredScore
		transaction.collection('uni-id-users').doc(user_id).update({
			score: newScore,
			grade: target_grade
		})
		// 6. 插入会员记录
		transaction.collection('jlg-member').add({
			user_id: user_id,
			grade: target_grade, // 存储等级文档ID
			opening_time: openingTime,
			failure_time: failureTime
		})
		// 7. 记录积分变动）
		transaction.collection('uni-id-scores').add({
			user_id,
			score: requiredScore,
			type: 2,
			balance: newScore,
			comment: '升级到'+gradeDoc.user_grade_name+'积分扣除',
			create_date: openingTime
		})
		// 8. 邀请人处理（
		if (userData.inviter_uid) {
			// 一级邀请人逻辑 
			const oneInviterRes = await transaction.collection('uni-id-users').doc(userData.inviter_uid).get()
			const oneInviterData = oneInviterRes.data
			if(!oneInviterData.grade){
				// 提交事务
				await transaction.commit()
				return
			}
			const oneInviterGradeRes = await transaction.collection('jlg-parameter').doc(oneInviterData.grade).get()
			const oneInviterGradeDoc = oneInviterGradeRes.data
			
			const res = await uniCloud.callFunction({
				name: 'uni-id-scores',
				data: {
					user_id: userData.inviter_uid,
					score: parseInt(requiredScore * (oneInviterGradeDoc.one_pro / 100)),
					type: 1,
					comment: userData.nikename+'用户升级会员一级返积分'
				}
			})
			//二级邀请人
			if (oneInviterData && oneInviterData.inviter_uid) {
				const twoInviterRes = await transaction.collection('uni-id-users').doc(oneInviterData.inviter_uid).get()
				const twoInviterData = twoInviterRes.data
				if(!twoInviterData.grade){
					// 提交事务
					await transaction.commit()
					return
				}
				const twoInviterGradeRes = await transaction.collection('jlg-parameter').doc(twoInviterData.grade).get()
				const twoInviterGradeDoc = twoInviterGradeRes.data
				
				const res2 = await uniCloud.callFunction({
					name: 'uni-id-scores',
					data: {
						user_id: oneInviterData.inviter_uid,
						score: parseInt(requiredScore * (twoInviterGradeDoc.two_pro / 100)),
						type: 1,
						comment: userData.nikename+'升级会员二级返积分'
					}
				})
			}


		}

		// 提交事务
		await transaction.commit()

		return {
			code: 200,
			msg: '升级成功',
			data: {
				new_grade: target_grade,
				new_score: newScore,
				validity: failureTime
			}
		}

	} catch (e) {
		// // 回滚事务（安全判断）
		await transaction.rollback()
		return {
			code: 500,
			msg: `升级失败：${e.message}`,
			debug: process.env.NODE_ENV === 'development' ? e.stack : undefined
		}
	}
}